import {
  defineStore
} from "pinia";
import userAPI from "@/api/user";
import router from "@/router/index";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: sessionStorage.getItem("token"),
    userInfo: sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")) : {},
    type: 0
  }),
  actions: {
    // 设置type(保留历史)
    setType(type) {
      this.type = type
    },
    // 登录成功后将返回的 token 存起来
    login({
      username,
      password
    }) {
      userAPI.login({
        username,
        password
      }).then((res) => {
        this.token = res.data.token;
        sessionStorage.setItem("token", res.data.token);
        this.getUserInfo()
      });
      return
    },
    getUserInfo() {
      userAPI.getUserInfo().then((res = {}) => {
        this.userInfo = res.data.user;
        console.log('-----userInfo-----', res);
        sessionStorage.setItem("userInfo", JSON.stringify(res.data.user));
      });
    },
    // 清空 token 和角色并跳转到登录页
    logout() {
      this.token = "";
      sessionStorage.removeItem("token");
      router.push("/login");
    },
  },
});